#include "port_exit.h"
#include "driver/gpio.h"
#include "freertos/FreeRTOS.h"
#include "freertos/task.h"

#define EXIT_CH_MAX_NUM (2)
#define IS_EXIT_CH(ch) ((ch) < EXIT_CH_MAX_NUM)
#define ESP_INTR_FLAG_DEFAULT 0


uint8_t exit_ch[EXIT_CH_MAX_NUM] = {GPIO_EXIT_CH0,GPIO_EXIT_CH1};

void exit_init(uint8_t ch, Pv_func_t cbk_func, exit_int_trigger_t trigger)
{
    if(IS_EXIT_CH(ch))
    {
        gpio_config_t io_conf;
        io_conf.intr_type =  (gpio_int_type_t)trigger;
        io_conf.pin_bit_mask = 1ULL << exit_ch[ch];
        io_conf.mode = GPIO_MODE_INPUT;
        io_conf.pull_down_en = 0;
        io_conf.pull_up_en = 0;
        gpio_config(&io_conf);

        gpio_install_isr_service(ESP_INTR_FLAG_DEFAULT);
        gpio_isr_handler_add(exit_ch[ch], cbk_func, (void*) exit_ch[ch]);
    }

}

void exit_set_trigger_mode(uint8_t ch, exit_int_trigger_t trigger)
{
    if(IS_EXIT_CH(ch))
    {
        gpio_set_intr_type(exit_ch[ch], (gpio_int_type_t)trigger);
    }
}

void exit_cmd(uint8_t ch, uint8_t enable)
{
    if(IS_EXIT_CH(ch))
    {
        if(enable == 0)
        {
            gpio_intr_enable(exit_ch[ch]);
        }
        else
        {
            gpio_intr_disable(exit_ch[ch]);
        }
    }
}